package com.rency.ues.webapp.controller;

import com.rency.ues.webapp.common.BaseAction;
import com.rency.ues.webapp.common.Constants;
import com.rency.ues.webapp.form.CertificationForm;
import org.rency.common.utils.security.X509CertUtils;
import org.rency.ues.common.UesDict;
import org.rency.ues.domain.request.CreateCertificationRequest;
import org.rency.ues.domain.response.CreateCertificationResponse;
import org.rency.ues.engine.service.CertificationService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;

/**
 * ${todo}
 *
 * @author: Created by user_rcy@163.com on 2016/8/1.
 * @version: V1.0.0
 * @since JDK 1.8
 */
@Controller
@RequestMapping("/certification")
public class CertificationController extends BaseAction {

    @Resource(name="certificationService")
    private CertificationService certificationService;

    @RequestMapping(value="createView.htm",method= RequestMethod.GET)
    public ModelAndView createView(){
        this.clear();
        return this.view(Constants.VM_PATH_PREFIX_CERTIFICATION,"create");
    }

    @RequestMapping(value="create.htm",method= RequestMethod.POST)
    public ModelAndView create(CertificationForm certForm){
        logger.info("开始创建证书,请求:{}.",certForm);
        CreateCertificationRequest request = new CreateCertificationRequest();
        request.setAliasName(certForm.getAliasName());
        request.setOrgiEmail(certForm.getOrgiEmail());
        request.setOrgiSimpleName(certForm.getOrgiSimpleName());
        request.setPassword(X509CertUtils.generateRandomKey(UesDict.DEFAULT_PASSWORD_KEY_LENGTH));
        CreateCertificationResponse response = certificationService.create(request);
        if(!response.isSuccess()){
            logger.info("创建证书失败.response:{},request:{}.",response,request);
            this.failed(response.getReturnMessage());
        }else{
            logger.info("创建证书成功.response:{}.",response);
            respData.put("serialNo",response.getSerialNo());
            this.success(response.getReturnMessage());
        }
        respData.put("form",certForm);
        return this.view(Constants.VM_PATH_PREFIX_CERTIFICATION,"create");
    }
}